package com.iconmaker.controller;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;

import com.bckim.iconmaker.R;
import com.iconmaker.command.CommandManager;
import com.iconmaker.model.Conf;
import com.iconmaker.model.Position;
import com.iconmaker.model.State;
import com.iconmaker.view.HScrollView;
import com.iconmaker.view.PixcelView;
import com.iconmaker.view.VScrollView;

public class CanvasActivity extends Activity {
	
	private static final int REQUEST_CODE_GET_IMAGE = 100;
	
	private CanvasEventListener eventListener;
	private static CanvasActivity instance;
	private LinearLayout pixcelContainerView;
	private VScrollView vScrollView;
	private HScrollView hScrollView;
	private RelativeLayout titlebar;
	private int statusBarHeight;
	private int canvasWidth;
	private int canvasHeight;

	
	private boolean needSave = true;
	
	public static final String KEY_LOAD_IMAGE_NAME = "loadImageName";
	
	public static CanvasActivity getContext() {
		return instance;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_canvas);
		
		if(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isFirst", true))
			startActivity(new Intent(this, GuideActivity.class));
		
		instance = this;
		
		State.canvasState = null;
		State.writeMode = 0;
		State.touchMode = 10;
		State.COLOR = Color.BLUE;
		State.canvasState = null;
		State.minimapHeightRatio = 0;
		State.minimapWidthRatio = 0;
		CommandManager.clear();
		
		statusBarHeight = getStatusBarHeight();
		
		Intent intent = getIntent();
		
		if(intent != null) {
			State.loadImageName = intent.getStringExtra(KEY_LOAD_IMAGE_NAME);
			
			if(State.loadImageName != null && !State.loadImageName.equals("new")) {
				File file = new File(Conf.rootPath + this.getPackageName() + "/" + State.loadImageName);
				
				if(file.exists()) {
					Bitmap bitmap = BitmapFactory.decodeFile(Conf.rootPath + this.getPackageName() + "/" + State.loadImageName);
					Conf.countOfColumnPixcel = bitmap.getWidth();
					Conf.countOfRowPixcel = bitmap.getHeight();
					
					State.canvasState = new int[Conf.countOfRowPixcel][Conf.countOfColumnPixcel];
					for(int i = 0; i < Conf.countOfRowPixcel; i++) {
						for(int j = 0; j < Conf.countOfColumnPixcel; j++) {
							State.canvasState[i][j] = bitmap.getPixel(i, j);
						}
					}
				}
			}
		}
		
		if(State.canvasState == null) {
			State.loadImageName = DataManager.getDatte() + ".png";
			State.canvasState = new int[Conf.countOfRowPixcel][Conf.countOfColumnPixcel];
			
			for(int i = 0; i < Conf.countOfRowPixcel; i++) {
				for(int j = 0; j < Conf.countOfColumnPixcel; j++) {
					State.canvasState[i][j] = Conf.defaultColor;
				}
			}
		}
		
		pixcelContainerView = (LinearLayout)findViewById(R.id.pixelConatiner);
		vScrollView = (VScrollView)findViewById(R.id.vScroll);
		hScrollView = (HScrollView)findViewById(R.id.hScroll);
		titlebar = (RelativeLayout)findViewById(R.id.titlebar);
		
		LinearLayout pixcelRowView = null;
		LayoutParams rowLayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		PixcelView pixcelView = null;
		
		for(int i = 0; i < Conf.countOfRowPixcel; i++) {
			pixcelRowView = new LinearLayout(this);
			pixcelRowView.setLayoutParams(rowLayout);
			
			for(int j = 0; j < Conf.countOfColumnPixcel; j++) {
				pixcelView = new PixcelView(this);
				pixcelView.setSize(Conf.pixcelSize, Conf.pixcelSize);
				pixcelView.setBackgroundColor(State.canvasState[j][i]);
				pixcelRowView.addView(pixcelView);
			}
			
			pixcelContainerView.addView(pixcelRowView);
		}
		
		eventListener = new CanvasEventListener(this);
		((ImageButton)findViewById(R.id.colorPickerBtn)).setColorFilter(State.COLOR, Mode.MULTIPLY);
		findViewById(R.id.colorPickerBtn).setOnClickListener(eventListener);
		findViewById(R.id.penPickerBtn).setOnClickListener(eventListener);
		findViewById(R.id.undoBtn).setOnClickListener(eventListener);
		findViewById(R.id.redoBtn).setOnClickListener(eventListener);
		findViewById(R.id.eraserBtn).setOnClickListener(eventListener);
		findViewById(R.id.importBtn).setOnClickListener(eventListener);
		findViewById(R.id.exportBtn).setOnClickListener(eventListener);
		findViewById(R.id.bucketBtn).setOnClickListener(eventListener);
		findViewById(R.id.imgView_preview).setOnTouchListener(eventListener);
		eventListener.refreshMinimap();
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		
		if(State.minimapHeightRatio == 0 || State.minimapWidthRatio == 0) {
			canvasWidth = pixcelContainerView.getWidth();
			canvasHeight = pixcelContainerView.getHeight();
			int scrollWidth = hScrollView.getWidth();
			int scrollHeight = vScrollView.getHeight();
			
			View minimap = findViewById(R.id.imgView_preview);
			View minimapPosition = findViewById(R.id.minimapPositionView);
			int minimapWidth = minimap.getWidth();
			int minimapHeight = minimap.getHeight();
			State.minimapWidthRatio = canvasWidth / minimapWidth;
			State.minimapHeightRatio = canvasHeight / minimapHeight;
			
			minimapPosition.setLayoutParams(new RelativeLayout.LayoutParams(scrollWidth / State.minimapWidthRatio, scrollHeight / State.minimapHeightRatio));
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getY() - statusBarHeight - titlebar.getHeight() < vScrollView.getHeight())
			eventListener.onTouchEvent(event);
		
		return super.onTouchEvent(event);
	}
	
	public int getViewXIndex(float postion) {
		return (int)((postion + hScrollView.getScrollX()) / (Conf.pixcelDimensionSize));
	}
	
	public int getViewYIndex(float postion) {
		return (int)((postion + vScrollView.getScrollY() - titlebar.getHeight() - statusBarHeight) / (Conf.pixcelDimensionSize));
	}
	
	public PixcelView getView(int xIndex, int yIndex) {
		if(pixcelContainerView == null)
			pixcelContainerView = (LinearLayout)CanvasActivity.getContext().findViewById(R.id.pixelConatiner);
		
		if(pixcelContainerView.getChildCount() > yIndex) {
			LinearLayout row = (LinearLayout)pixcelContainerView.getChildAt(yIndex);
			if(row.getChildCount() > xIndex)
				return (PixcelView)row.getChildAt(xIndex);
		}
		
		return null;
	}
	
	public ArrayList<PixcelView> getView(ArrayList<Position> list) {
		if(pixcelContainerView == null)
			pixcelContainerView = (LinearLayout)CanvasActivity.getContext().findViewById(R.id.pixelConatiner);
		
		ArrayList<PixcelView> resultList = new ArrayList<PixcelView>();
		
		int xIndex;
		int yIndex;
		
		for(Position position : list) {
			xIndex = position.getX();
			yIndex = position.getY();
			
			if(pixcelContainerView.getChildCount() > yIndex) {
				LinearLayout row = (LinearLayout)pixcelContainerView.getChildAt(yIndex);
				if(row.getChildCount() > xIndex)
					resultList.add((PixcelView)row.getChildAt(xIndex));
			}
		}
		
		return resultList;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	public int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if(resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}
	
	@Override
	protected void onPause() {
		if(needSave)
			DataManager.save(pixcelContainerView, State.loadImageName);
		
		super.onPause();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == REQUEST_CODE_GET_IMAGE) {
			if(resultCode == Activity.RESULT_OK) {
				needSave = true;
				Uri uri = data.getData();
				String scheme = uri.getScheme();
				String path = null;
				
				if(scheme.equals("file")) {
					path = uri.getPath();
				}
				else if(scheme.equals("content")) {
					Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
					int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					
					cursor.moveToFirst();
					path = cursor.getString(index);
					
					cursor.close();
				}
				
				if(path != null) {
					importImage(path);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	public void getImage() {
		needSave = false;
		
		Intent intent = new Intent(Intent.ACTION_PICK);
		
		intent.setType("image/*");
		
		this.startActivityForResult(intent, REQUEST_CODE_GET_IMAGE);
	}
	
	public void importImage(String path) {
		Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), Conf.countOfColumnPixcel, Conf.countOfRowPixcel, false);
		
		LinearLayout row;
		
		for(int i = 0; i < Conf.countOfRowPixcel; i++) {
			row = (LinearLayout)pixcelContainerView.getChildAt(i);
			for(int j = 0; j < Conf.countOfColumnPixcel; j++) {
				State.canvasState[i][j] = bitmap.getPixel(i, j);
				((PixcelView)row.getChildAt(j)).setBackgroundColor(State.canvasState[i][j]);
			}
		}
		
		bitmap.recycle();
	}
	//	public void importImage(String path) {
	//		Bitmap bitmap = BitmapFactory.decodeFile(path);
	//		
	//		int width = bitmap.getWidth();
	//		int height = bitmap.getHeight();
	//		
	//		if(width == Conf.countOfColumnPixcel && height == Conf.countOfRowPixcel) {
	//			LinearLayout row;
	//			
	//			for(int i = 0; i < Conf.countOfRowPixcel; i++) {
	//				row = (LinearLayout)pixcelContainerView.getChildAt(i);
	//				for(int j = 0; j < Conf.countOfColumnPixcel; j++) {
	//					State.canvasState[i][j] = bitmap.getPixel(i, j);
	//					((PixcelView)row.getChildAt(j)).setBackgroundColor(State.canvasState[i][j]);
	//				}
	//			}
	//		}
	//		else {
	//			new AlertDialog.Builder(this).setMessage("이미즈 사이즈를 확인해 주세").setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
	//				
	//				@Override
	//				public void onClick(DialogInterface dialog, int which) {
	//					dialog.cancel();
	//				}
	//			}).setTitle("알림").show();
	//		}
	//		
	//		bitmap.recycle();
	//	}
}
